<template>
  <FIModel
    title="新增流程"
    width="1000"
    v-model="showModel"
    :confirmLoading="confirmLoading"
    @close="closeClick"
    @confirm="saveFunc(ruleFormRef)"
  >
    <!-- <FIPanel use-collapse title="任务信息"></FIPanel> -->
    <FIForm ref="ruleFormRef " :model="ruleForm" :rules="rules" label-width="100px" :size="formSize">
      <el-row :gutter="20">
        <el-col :span="wrapperSpan" class="flex-center">
          <FIFormItem name="userCName" label="用户">
            <FISelect
              v-model="ruleForm.userId"
              valueCustom="loginName"
              :props="{ value: 'loginName', label: 'userCName' }"
              :options="userArr"
              :display-key="['loginName', 'userCName']"
              filterable
              @select="handleSelectUser"
            />
            <!-- <FISelect
              v-model="ruleForm.userId"
              valueCustom="userCName"
              :props="{ value: 'loginName', label: 'userCName' }"
              :displayKey="['loginName', 'userCName']"
              :options="userArr"
              filterable
              @select="
                (item) => {
                  ruleForm.userCName = item.userCName
                }
              "
            /> -->
            <!-- <FIAutoInput
              v-model="ruleForm.userCName"
              :options="userArr"
              value-key="userCName"
              :displayKey="['loginName', 'userCName']"
              placeholder="请输入"
              @select="
                (item) => {
                  ruleForm.userId = item.loginName
                }
              "
            >
              <template #default="{ item }">
                <span>{{ item.loginName }}</span
                >-<span>{{ item.userCName }}</span>
              </template>
            </FIAutoInput> -->
          </FIFormItem>
        </el-col>
        <el-col :span="wrapperSpan" class="flex-center">
          <FIFormItem name="roleCname" label="角色名称">
            <FISelect
              v-model="ruleForm.roleEname"
              valueCustom="roleId"
              :props="{ value: 'roleId', label: 'roleName' }"
              :options="roleList"
              @change="handleSelectRole"
            />
            <!-- <FIAutoInput
              v-model="ruleForm.roleCname"
              :options="roleList"
              value-key="roleName"
              :displayKey="['roleId', 'roleName']"
              placeholder="请输入"
              clearable
              @select="
                (item) => {
                  ruleForm.roleEname = item.roleId
                }
              "
            >
              <template #default="{ item }">
                <span>{{ item.roleId }}</span
                >-<span>{{ item.roleName }}</span>
              </template>
            </FIAutoInput> -->
          </FIFormItem>
        </el-col>
        <el-col :span="wrapperSpan" class="flex-center">
          <FIFormItem name="deptCname" label="部门名称">
            <FISelect
              v-model="ruleForm.deptEname"
              valueCustom="deptId"
              :props="{ value: 'deptId', label: 'deptName' }"
              :options="deptList"
              @change="handleSelectDept"
            />
            <!-- <FIAutoInput
              v-model="ruleForm.deptCname"
              :options="deptList"
              value-key="deptName"
              :displayKey="['deptId', 'deptName']"
              placeholder="请输入"
              clearable
              @select="
                (item) => {
                  ruleForm.deptEname = item.deptId
                }
              "
            >
              <template #default="{ item }">
                <span>{{ item.deptId }}</span
                >-<span>{{ item.deptName }}</span>
              </template>
            </FIAutoInput> -->
          </FIFormItem>
        </el-col>
        <el-col :span="wrapperSpan" class="flex-center">
          <FIFormItem name="hasAuth" label="是否授权">
            <FISelect
              v-model="ruleForm.hasAuth"
              :options="[
                { value: 'true', label: '是' },
                { value: 'false', label: '否' },
              ]"
              clearable
            />
          </FIFormItem>
        </el-col>
        <el-col :span="wrapperSpan" class="flex-center">
          <FIFormItem name="claimStatus" label="是否领取">
            <FISelect
              v-model="ruleForm.claimStatus"
              valueCustom="value"
              :options="[
                { value: 'false', label: '不领取' },
                { value: 'true', label: '领取' },
              ]"
              clearable
            />
          </FIFormItem>
        </el-col>
      </el-row>
    </FIForm>
  </FIModel>
</template>
<script setup lang="ts">
import FIModel from '@/components/FIModel.vue'
import FIPanel from '@/components/FIPanel.vue'
import { onMounted, reactive, ref, watch, computed } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { apiRequestPost } from '@/api/globalApi.js'

import FIForm from '@/components/FIForm.vue'
import { apiQueryDelegate, apiQueryAccept } from '@/api/modules/EWPT.js'
import { useMessage } from '@/hooks/message'
const props = defineProps({
  type: {
    type: String,
    default: '',
  },
  visible: {
    type: Boolean,
    default: false,
  },
  userArr: {
    type: Array,
    default: () => [],
  },
  id: {
    type: String,
    default: '',
    required: true,
  },
})
const wrapperSpan = 8
const confirmLoading = ref(false)
const emits = defineEmits(['close', 'update:visible', 'confirm', 'save-ok'])
// const showModel = ref(props.visible)
let showModel = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val)
  },
})

watch(
  () => showModel.value,
  (val) => {
    if (showModel.value) {
      showModel.value = val
      // 初始化表单
      Object.keys(ruleForm).forEach((key) => {
        ruleForm[key] = ''
      })
    }
  }
)

interface RuleForm {
  userCName: string
  userName: string
  userId: string
  roleEname: string
  roleCname: string
  deptEname: string
  deptCname: string
  hasAuth: string
  claimStatus: string
  taskId: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<RuleForm>({
  userCName: '',
  userName: '',
  userId: '',
  roleEname: '',
  roleCname: '',
  deptEname: '',
  deptCname: '',
  hasAuth: 'true',
  claimStatus: 'true',
  taskId: props.id,
})
const rules = reactive<FormRules<RuleForm>>({
  userCName: [{ required: true, message: '请输入目录编码', trigger: 'blur' }],
  roleCname: [
    {
      required: true,
      message: '请输入目录名称',
      trigger: 'blur',
    },
  ],
  deptCname: [
    {
      required: false,
      message: '请输入描述',
      trigger: 'blur',
    },
  ],
})
const roleList = ref([])
const deptList = ref([])
watch(
  () => ruleForm.userId,
  (val, oldVal) => {
    console.log('ruleForm.userId', val, oldVal)
    if (val != oldVal) {
      ruleForm.roleEname = ''
      ruleForm.roleCname = ''
      ruleForm.deptEname = ''
      ruleForm.deptCname = ''
    }
    if (val) {
      // 获取角色信息，部门信息
      getRoleAddDeptList(val)
      getDeptList(val)
    }
  }
)
const handleSelectUser = (e) => {
  ruleForm.userCName = e?.userCName
  ruleForm.userName = e?.userCName
}
const handleSelectRole = (e) => {
  const selectedOption = roleList.value.find((item) => item.roleId === e)
  if (selectedOption) {
    ruleForm.roleCname = selectedOption.roleName
  }
}
const handleSelectDept = (e) => {
  const selectedOption = deptList.value.find((item) => item.deptId === e)
  if (selectedOption) {
    ruleForm.deptCname = selectedOption.deptName
  }
}
const getRoleAddDeptList = (val) => {
  let params = {
    userId: val,
  }
  apiQueryDelegate(params).then((res) => {
    if (res.data.success) {
      roleList.value = []
      deptList.value = []
      res.data.data.forEach((item: any) => {
        if (item?.roleId) {
          roleList.value.push(item)
        }
        // } else {
        //   deptList.value.push(item)
        // }
      })
    }
  })
}
const getDeptList = (val) => {
  let params = {
    userId: val,
  }
  apiQueryAccept(params).then((res) => {
    if (res.data.success) {
      deptList.value = res.data.data || []
    }
  })
}
const closeClick = () => {
  emits('update:visible', false)
  emits('close')
}

const saveFunc = async (formEl: FormInstance | undefined) => {
  // if (!formEl) return
  // await formEl.validate((valid, fields) => {
  //   if (valid) {
  //     emits('update:visible', false)
  //     emits('confirm')
  //     const obj = {
  //       key: ruleForm.key,
  //       name: ruleForm.name,
  //       desc: ruleForm.desc,
  //       operateMode: props.type,
  //       id: props.info.id,
  //     }
  //     if (props.type == 'update') {
  //       obj.parentId = props.info.parentId
  //     } else {
  //       obj.parentId = props.info.id
  //     }
  //     console.log(obj, '-------rops.info----', props.info)
  //     apiRequestPost('/bpm-service/BpmCategory/saveCategoryInfo', obj)
  //       .then((res) => {
  //         if (res.data.success) {
  //           emits('save-ok', res.data)
  //           // infoFormType.value = 'info'
  //           // loadNode()
  //           // loadNode(selectedNodeObj.value)
  //         } else {
  //         }
  //       })
  //       .catch((error: any) => {
  //         // 处理错误
  //       })
  //   } else {
  //     console.log('error submit!', fields)
  //   }
  // })

  emits('confirm')
  if (!ruleForm.userId) {
    useMessage().warning('请选择用户')
    return
  }
  ruleForm.taskId = props.id
  confirmLoading.value = true
  apiRequestPost('/bpm-service/TaskMaint/addTask', ruleForm)
    .then((res) => {
      confirmLoading.value = false
      if (res.data.success) {
        emits('save-ok', res.data)
        emits('update:visible', false)
      }
    })
    .catch(() => {
      confirmLoading.value = false
    })
}
onMounted(() => {})
</script>
